import React, { useState, useEffect } from "react";
import { Modal, Input, Button, message } from "antd";
import { sendEmailVerifyCode, checkEmailVerifyCode } from "@/api/xhr/user/index";

interface EmailVerifyModalProps {
  open: boolean;
  email: string;
  onCancel: () => void;
  onSuccess: () => void;
  type?: "register" | "update";
}

const EmailVerifyModal: React.FC<EmailVerifyModalProps> = ({
  open,
  email,
  onCancel,
  onSuccess,
  type = "update"
}) => {
  const [verifyCode, setVerifyCode] = useState("");
  const [loading, setLoading] = useState(false);
  const [sending, setSending] = useState(false);
  const [countdown, setCountdown] = useState(0);

  // 发送验证码
  const handleSendCode = async () => {
    if (!email) {
      message.error("请先输入邮箱地址");
      return;
    }
    try {
      setSending(true);
      const res = await sendEmailVerifyCode(email, type);
      if (res.statusCode === 200) {
        message.success("验证码已发送至您的邮箱");
        // 开始倒计时
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown(prev => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        message.error(res.errorInfo || "发送验证码失败");
      }
    } catch (error) {
      console.error("发送验证码出错:", error);
    } finally {
      setSending(false);
    }
  };

  // 验证验证码
  const handleVerify = async () => {
    if (!verifyCode) {
      message.error("请输入验证码");
      return;
    }

    try {
      setLoading(true);
      const res = await checkEmailVerifyCode(email, verifyCode, type);
      if (res.statusCode === 200) {
        message.success("验证成功");
        setVerifyCode("");
        onSuccess();
      } else {
        message.error(res.errorInfo || "验证码验证失败");
      }
    } catch (error) {
      console.error("验证失败:", error);
    } finally {
      setLoading(false);
    }
  };

  // 处理取消操作
  const handleCancel = () => {
    setVerifyCode("");
    onCancel();
  };

  // 当modal打开时，自动发送验证码
  useEffect(() => {
    if (open && email && countdown === 0) {
      handleSendCode();
    }
  }, [open, email]);

  return (
    <Modal
      title="邮箱验证"
      open={open}
      onCancel={handleCancel}
      footer={[
        <Button key="cancel" onClick={handleCancel}>
          取消
        </Button>,
        <Button 
          key="verify" 
          type="primary" 
          loading={loading} 
          onClick={handleVerify}
        >
          验证
        </Button>
      ]}
    >
      <div className="py-4">
        <p className="mb-4">验证码已发送至: {email}</p>
        <div className="flex items-center">
          <Input 
            placeholder="请输入验证码" 
            value={verifyCode}
            onChange={e => setVerifyCode(e.target.value)}
            className="flex-1 mr-2"
          />
          <Button 
            onClick={handleSendCode}
            disabled={countdown > 0} 
            loading={sending}
          >
            {countdown > 0 ? `${countdown}秒` : "重新发送"}
          </Button>
        </div>
      </div>
    </Modal>
  );
};

export default EmailVerifyModal; 